#include "Client.h"
#include "ClientServer.h"
#include "Exception.h"
#include <iostream>
Client::Client(const ServerInfo &serverInfo)
{
	remoteServer = new RemoteServer(serverInfo);
	taskInfo.taskStatus = TS_NO_STATUS;
	myThread = NULL;
}


Client::~Client(void)
{
	delete remoteServer;
	if(myThread !=NULL)
	 delete myThread;

}

 int Client::recived;

void Client::run()
{
	int evaq = 0;
	if(taskInfo.taskStatus == TS_ERROR) evaq = 1;
	while(evaq == 0)
	{
		boost::this_thread::sleep(boost::posix_time::seconds(2));
		TaskInfo taskInfo = getTaskInfo();
		//std::cout<<"Zadanie ID= "<<taskInfo.taskId <<std::endl;
		if(taskInfo.taskStatus == TS_DONE)
		{
			recived ++;
			evaq = 1;
			std::cout<<"Zadanie nr "<<recived << " ID= "<<taskInfo.taskId <<" zakonczylo sie powodzeniem, oto rezultat: "<<std::endl<<taskInfo.result.str;
		}
		if(taskInfo.taskStatus == TS_ERROR)
		{
			recived ++;
			evaq = 1;
			std::cout<<"Zadanie "<<recived <<"  ID= "<<taskInfo.taskId <<" zakonczylo sie bledem, oto rezultat dzialania: "<<std::endl<<taskInfo.result.str;
		}
	}
	std::cout<<std::endl;

}

void Client::start()
{
	myThread = new boost::thread(::run,this);	
}

void Client::sendTask(const std::string &atask)
{
	TaskMsg taskMsg;
	TaskRet taskRet;
	std::string ret;
	std::stringstream ss;
	taskMsg.task.str = atask;
	taskMsg.serialize(ss);
	try{
		ret = remoteServer->sendMessage(ss.str());
	}
	catch(NetExeption &exp)
	{
	}
	std::cout<<"sendTask ret = "<<ret<<std::endl;
	std::stringstream ssRet(ret);
	int x;
	ssRet>>x;
	taskRet.deSerialize(ssRet);
	std::cout<<"sendTask ID= "<<taskRet.taskInfo.taskId<<" "<<taskRet.taskInfo.result.str<<std::endl;
	taskInfo = taskRet.taskInfo;
	
}

TaskInfo Client::getTaskInfo()
{
	TaskCheckMsg taskCheck;
	TaskRet taskRet;
	taskCheck.taskId = taskInfo.taskId;
	
	std::stringstream ss;
	std::string ret;
	taskCheck.serialize(ss);
	
	try
	{
		ret = remoteServer->sendMessage(ss.str());
	}
	catch(NetExeption &exp)
	{
	}
	//std::cout<<"GetTaskInfo ret = "<<ret<<std::endl;
	std::stringstream ssRet(ret);
	int x;
	ssRet>>x;
	taskRet.deSerialize(ssRet);
	taskInfo = taskRet.taskInfo;
	return taskInfo;
	
}